/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package thread;

import canvas.MIDPCanvasPlay;
import java.io.IOException;
import java.util.Random;
import javax.microedition.lcdui.Image;

/**
 *
 * @author LTTDNQ
 */
public class threadTime implements Runnable {

    private MIDPCanvasPlay _canvas;

    public threadTime(MIDPCanvasPlay c) {
        this._canvas = c;
    }
    //Chạy luồng thời gian 5s rơi quả trứng

    public void run() {
        while (!_canvas.getStop()) {
            try {
                //Tạo trứng đầu tiên
                int n = _canvas.getSoItems() + 1;
                _canvas.setSoItems(n);
                taoItems();
                Thread.sleep(5000-400*(10 - _canvas.getLevel()));
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
    //Khi có nhiều hơn 1 con gà

    private void sapXepItems(int i) {
        try {
            boolean flag = true;
            Image img;
            //Random ra trứng và phân
            Random rand = new Random();
            int r = rand.nextInt(6);
            if (r < 2) {
                img = Image.createImage("/Images/shit.png");
                flag = false;
            } else {
                img = Image.createImage("/Images/egg.png");
            }
            r = rand.nextInt(_canvas.getSoGiaCam() + 1);
            if (r > 0) {
                r--;
            }
            //if(_canvas.getArrRunableItemsFall()[_canvas.getPreviousItems()].getViTriItemsY() != 62 || _canvas.getPreviousItems() == -1){

            _canvas.getArrRunableItemsFall()[i] = new RunableItemsFall(img, _canvas.getArrImage()[r].getX() + 5, 62, _canvas, i, flag);
            _canvas.setPreviousItems(i);

            //}
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        new Thread(_canvas.getArrRunableItemsFall()[i]).start();
    }

    private void taoItems() throws IOException {
        if (_canvas.getSoItems() > 0) {
            for (int i = 0; i < _canvas.getSoItems() - 1; i++) {
                if (_canvas.getArrRunableItemsFall()[i] == null) {
                    sapXepItems(i);
                    break;
                }
            }
        }
    }
}
